/***************************************************************************
 *   Copyright (C) 2007 by Gaetano Mendola  *
 *   mendola@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "eventdispatcher.h"
#include "eventsink.h"

namespace Events {

EventDispatcher& EventDispatcher::instance() 
{
    static EventDispatcher theDispatcher;

    return theDispatcher;
}

void EventDispatcher::subscribe(Events::Event::TYPE anEvent, EventSink* aSink)
{
    theSinks[anEvent].insert ( aSink );
}

void EventDispatcher::unsubscribe(Events::Event::TYPE anEvent, EventSink* aSink)
{
    TheEventSinkMap::iterator myIt = theSinks.find( anEvent );
    if ( myIt == theSinks.end() ) { 
        //no sinks at all for the event
    } else {
        theSinks[anEvent].erase ( aSink );
    }
}

void EventDispatcher::unsubscribe(EventSink* aSink)
{
    TheEventSinkMap::iterator myIt = theSinks.begin();
    TheEventSinkMap::const_iterator myItEnd = theSinks.end();
    for ( /*void*/ ; myIt != myItEnd; ++myIt ) {
        (*myIt).second.erase(aSink);
    }
}

void EventDispatcher::notify(const Events::Event* anEvent)
{
    TheEventSinkMap::iterator myIt = theSinks.find( anEvent->type() );
    if (myIt == theSinks.end() ) {
        //noone subscribed for the event
        delete anEvent;
        return;
    }

    TheSinksSet::iterator       mySinkIt    = (*myIt).second.begin();
    TheSinksSet::const_iterator mySinkItEnd = (*myIt).second.end();

    for ( /*void*/ ; mySinkIt != mySinkItEnd; ++mySinkIt ) {
        (*mySinkIt)->notify(anEvent);
    }

    //the event can be destroyed now
    delete anEvent;
}

EventDispatcher::EventDispatcher()
:theSinks()
{
}


EventDispatcher::~EventDispatcher()
{
}


}
